from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
from asgiref.sync import async_to_sync


# USER_LIST = []


class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        # 服务端允许连接
        self.accept()
        # USER_LIST.append(self)
        # 发送成功连接消息
        # self.send("连接成功")
        # 使用channel内置的layers存储
        group = self.scope['url_route']['kwargs'].get("group")
        async_to_sync(self.channel_layer.group_add)(group, self.channel_name)
        async_to_sync(self.channel_layer.group_send)(group, {'type': 'open_send',
                                                             'message': {'type': 'websocket.receive',
                                                                         'text': '[连接成功]'}})

    def open_send(self, event):
        text = "[连接成功]"
        self.send(text)

    def websocket_receive(self, message):
        res = "{}".format(message['text'])
        if res == "关闭":
            self.close()
            return
        group = self.scope['url_route']['kwargs'].get("group")
        async_to_sync(self.channel_layer.group_send)(group, {'type': "fg.send", 'message': message})
        # for user in USER_LIST:
        #     user.send(res)

    def fg_send(self, event):
        text = event['message']['text']
        self.send(text)

    def websocket_disconnect(self, message):
        # USER_LIST.remove(self)
        group = self.scope['url_route']['kwargs'].get("group")
        async_to_sync(self.channel_layer.group_discard)(group, self.channel_name)
        async_to_sync(self.channel_layer.group_send)(group, {'type': 'close_send',
                                                             'message': {'type': 'websocket.receive',
                                                                         'text': '[连接成功]'}})
        raise StopConsumer()

    def close_send(self, event):
        text = "[断开连接]"
        self.send(text)
